package com.lemner.ke.util;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 相机和相册工具类.
 *
 * @author 杨烨
 * @date 2018/9/10
 */
public class PhotoAlbumUtil {
    @Nullable
    public static Bitmap getBitmapFromUri(Context context, Uri uri) {
        try {
            return MediaStore.Images.Media.getBitmap(context.getContentResolver(), uri);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Bitmap zoomImage(Context context, Bitmap bm) {
        //获取屏幕分辨率
        DisplayMetrics dm = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(dm);
        float dw = dm.widthPixels;
        float dh = dm.heightPixels;
        // 获得图片的宽高
        int width = bm.getWidth();
        int height = bm.getHeight();
        float newWidth, newHeight;
        if (width > height) {
            if (bm.getWidth() < dw)
                return bm;
            newWidth = dw;
            newHeight = bm.getHeight() / (bm.getWidth() / dw);
        } else {
            if (bm.getHeight() < dh)
                return bm;
            newWidth = bm.getWidth() / (bm.getHeight() / dh);
            newHeight = dh;
        }
        // 计算缩放比例
        float scaleWidth = (newWidth) / width;
        float scaleHeight = (newHeight) / height;
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的图片
        Bitmap bitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
        return bitmap;
    }

    public static File saveFile(Bitmap bm, String path, String fileName) {
        File dirFile = new File(path);
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }
        File myCaptureFile = new File(path, fileName);
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
            bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
            bos.flush();
            bos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return myCaptureFile;
    }
}
